<template>
    <div class="platform-user">
        <div class="platform-user-org-tree">
            <el-tree
                    default-expand-all
                    :expand-on-click-node="false"
                    @node-click="handleOrgTreeClick"
                    :data="orgTree"
                    :props="orgTreeProps">
            </el-tree>
        </div>
        <div class="platform-user-table">
            <el-form :inline="true" :model="searchForm" size="mini">
                <el-form-item label="账号">
                    <el-input v-model="searchForm.account" placeholder="账号"></el-input>
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.username" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                    <el-button type="primary" @click="listUser">刷新</el-button>
                    <el-button type="primary" @click="handleCreate">新建</el-button>
                    <el-button type="primary" @click="setRoomUser">批量分配房间</el-button>
                    <el-button type="danger" @click="unBindRoomUser">批量删除用户</el-button>
                </el-form-item>
            </el-form>
            <el-table
                    :data="tableData"
                    style="width: 100%; margin-bottom: 20px;"
                    row-key="id"
                    border
                    default-expand-all
                    stripe
                    size="mini"
                    @row-dblclick="handleRowDblclick"
                    @selection-change="handleSelectionChange"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        prop="account"
                        label="账号"
                        width="150"
                        min-width="100">
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="用户名"
                        width="120">
                </el-table-column>
                <el-table-column
                        label="角色"
                        width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.roles != null" v-for="(item, index) in scope.row.roles" :key="index">
                          {{ item.name }},
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="状态"
                        width="100">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == '1'" type="success" size="mini">启用</el-tag>
                        <el-tag v-if="scope.row.status == '0'" type="danger" size="mini">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="sort"
                        label="排序"
                        width="100">
                </el-table-column>
                <el-table-column
                        :formatter="dateFormatter"
                        prop="gmtCreate"
                        label="创建时间"
                        width="150">
                </el-table-column>
                <el-table-column
                        :formatter="dateFormatter"
                        prop="gmtModified"
                        label="修改时间"
                        width="150">
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="250">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleResetPassword(scope.$index, scope.row)">重置密码
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <dormitory-pagination :parent-method="listUser"
                                  :pagination="this.$store.state.Navigation.pagination"></dormitory-pagination>
            <el-dialog :close-on-click-modal="false" title="用户管理" :visible.sync="dialogFormVisible" label-width="80px">
                <el-form ref="form" :model="userForm" label-width="80px">
                    <el-form-item label="账号">
                        <el-input v-model="userForm.account"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" v-if="!isUpdate">
                        <el-select v-model="userForm.passwordType" placeholder="密码类型" style="width: 30%">
                            <el-option label="默认密码" value="1"></el-option>
                            <el-option label="随机密码" value="2"></el-option>
                            <el-option label="自定义" value="3"></el-option>
                        </el-select>
                        <el-input v-model="userForm.password" v-if="userForm.passwordType == '3'"
                                  style="width: 70%"></el-input>
                    </el-form-item>
                    <el-form-item label="用户名">
                        <el-input v-model="userForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                            <el-option
                                    v-for="item in roles"
                                    :key="item.ukId"
                                    :label="item.name"
                                    :value="item.ukId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属机构">
                        <tree-select
                                :showCount="true"
                                :openOnClick="true"
                                :defaultExpandLevel="3"
                                noChildrenText="无下级机构"
                                v-model="userForm.orgId"
                                :options="orgTree"
                                :normalizer="orgTreeNormalizer">
                        </tree-select>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select v-model="userForm.status" placeholder="请选择状态">
                            <el-option label="启用" :value="1"></el-option>
                            <el-option label="停用" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-select v-model="userForm.userInfo.gender" placeholder="请选择性别">
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="userForm.sort" type="number" min="0" max="90000"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSave">保存</el-button>
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog :close-on-click-modal="false" title="批量分配房间" :visible.sync="dialogRoomUserFormVisible"
                       label-width="80px">
                <el-form ref="form" :model="roomUserForm" label-width="140px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="房间类型（男）">
                                <el-select
                                        @change="roomTypeChange(1)"
                                        v-model="roomUserForm.boy.roomType"
                                        style="width: 100%">
                                    <el-option
                                            v-for="item in boyRoomType"
                                            :key="item.type"
                                            :label="item.type + '人间'"
                                            :value="item.type">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="起始楼号（男）">
                                <el-select
                                        @change="buildingNumChange(1)"
                                        v-model="roomUserForm.boy.buildingNum"
                                        style="width: 100%">
                                    <el-option
                                            v-for="item in boyBuildingList"
                                            :key="item.ukId"
                                            :label="item.name"
                                            :value="item.ukId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="起始房间号（男）">
                                <el-select v-model="roomUserForm.boy.roomNum" style="width: 100%">
                                    <el-option
                                            v-for="item in boyRoomList"
                                            :key="item.ukId"
                                            :label="item.name + ' 已住' +item.count"
                                            :value="item.ukId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="房间类型（女）">
                                <el-select
                                        @change="roomTypeChange(0)"
                                        v-model="roomUserForm.girl.roomType" style="width: 100%">
                                    <el-option
                                            v-for="item in girlRoomType"
                                            :key="item.type"
                                            :label="item.type + '人间'"
                                            :value="item.type">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="起始楼号（女）">
                                <el-select
                                        @change="buildingNumChange(0)"
                                        v-model="roomUserForm.girl.buildingNum" style="width: 100%">
                                    <el-option
                                            v-for="item in girlBuildingList"
                                            :key="item.ukId"
                                            :label="item.name"
                                            :value="item.ukId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="起始房间号（女）">
                                <el-select v-model="roomUserForm.girl.roomNum" style="width: 100%">
                                    <el-option
                                            v-for="item in girlRoomList"
                                            :key="item.ukId"
                                            :label="item.name + ' 已住' +item.count"
                                            :value="item.ukId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="dialogRoomUserFormVisible = false">取 消</el-button>
                                <el-button type="primary" @click="batchBindRoomUser">保存</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-dialog>
        </div>
        <el-drawer
                title="用户信息"
                :visible.sync="drawerFormVisible"
                direction="rtl">
        </el-drawer>
    </div>
</template>

<script>
    import TreeSelect from '@riophae/vue-treeselect'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import DormitoryPagination from "../../components/DormitoryPagination";

    import {listOrgTree} from "../../../../api/platform/org";
    import {listRole} from "../../../../api/platform/role";
    import {
        listUser,
        listUserByOrgId,
        saveUser,
        createUser,
        updateUser,
        deleteUser,
        resetUserPassword
    } from "../../../../api/platform/user";

    import {listBuilding, listBuildingType} from "../../../../api/manage/building";

    import PageSizeUtils from "../../../../utils/PageSizeUtils";
    import {listRoomByBuildingId, batchBindRoomUser, batchUnBindRoomUser} from "../../../../api/manage/room";

    export default {
        name: "User",
        components: {TreeSelect, DormitoryPagination},
        data() {
            return {
                tableData: [],
                orgTree: [],
                orgTreeProps: {
                    children: 'children',
                    label: 'name'
                },
                orgTreeNormalizer(node) {
                    if (!node.children.length) {
                        delete node.children;
                    }
                    return {
                        id: node.ukId,
                        label: node.name
                    }
                },
                roles: [],
                dialogFormVisible: false,
                drawerFormVisible: false,
                dialogRoomUserFormVisible: false,
                userForm: {
                    orgId: "",
                    account: "",
                    password: "",
                    username: "",
                    passwordType: "1",
                    status: 1,
                    sort: 10000,
                    roleIds: [],
                    userInfo: {
                        gender: "1",
                    }
                },
                roomUserForm: {
                    boy: {
                        roomType: "",
                        buildingNum: "",
                        roomNum: ""
                    },
                    girl: {
                        roomType: "",
                        buildingNum: "",
                        roomNum: ""
                    },
                    users: []
                },
                boyRoomType: [],
                boyBuildingList: [],
                boyRoomList: [],
                girlRoomType: [],
                girlBuildingList: [],
                girlRoomList: [],
                searchForm: {},
                isUpdate: false
            };
        },
        methods: {
            listUser(current, size) {
                listUser(this.searchForm, current, size).then(response => {
                    this.tableData = response.data.users.records
                    PageSizeUtils.setPagination(response.data.users)
                }).catch(error => {
                    console.log(error)
                })
            },
            handleCreate(index, row) {
                this.isUpdate = false
                this.listRole()
                this.userForm = {
                    userInfo: {
                        gender: "1"
                    }
                }
                this.dialogFormVisible = true;
            },
            handleEdit(index, row) {
                this.isUpdate = true
                this.listRole()
                this.dialogFormVisible = true;
                this.userForm = row
            },
            handleDelete(index, row) {
                deleteUser(row.ukId).then(response => {
                    this.listUser();
                }).catch(error => {
                    console.log(error)
                })
            },
            handleResetPassword(index, row) {
                this.$confirm('是否确认重置密码?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    resetUserPassword(row.ukId).then(response => {
                        this.$notify({
                            title: '成功',
                            message: '密码重置成功！初始密码为123456！',
                            type: 'success'
                        });
                        this.listUser();
                    }).catch(error => {
                        console.log(error)
                    })
                }).catch(() => {
                    this.$notify.info({
                        title: '消息',
                        message: '已取消重置密码'
                    });
                });
            },
            handleSearch() {
                this.listUser(this.$store.state.Navigation.pagination.current,
                    this.$store.state.Navigation.pagination.size)
            },
            handleReset() {
                this.searchForm = {}
            },
            handleSave() {
                if (this.isUpdate) {
                    updateUser(this.userForm).then(response => {
                        this.listUser();
                        this.dialogFormVisible = false;
                    }).catch(error => {
                        console.log(error)
                    })
                } else {
                    createUser(this.userForm).then(response => {
                        this.listUser();
                        this.dialogFormVisible = false;
                    }).catch(error => {
                        console.log(error)
                    })
                }
            },
            handleOrgTreeClick(data) {
                listUserByOrgId(data.ukId).then(response => {
                    console.log(response.data.users)
                    this.tableData = response.data.users
                    PageSizeUtils.setPagination(response.data.users)
                }).catch(error => {
                    console.log(error)
                })
            },
            handleRowDblclick(row, column, event) {
                this.drawerFormVisible = true
            },
            dateFormatter(row, column, cellValue, index, type) {
                let replace = cellValue.replace("T", " ");
                return replace.substring(0, 19);
            },
            listRole() {
                listRole().then(response => {
                    this.roles = response.data.roles.records
                }).catch(error => {
                    console.log(error)
                })
            },
            setRoomUser() {
                listBuildingType(1).then(response => {
                    this.boyRoomType = response.data.types
                }).catch(error => {
                    console.log(error)
                })
                listBuildingType(0).then(response => {
                    this.girlRoomType = response.data.types
                }).catch(error => {
                    console.log(error)
                })
                this.dialogRoomUserFormVisible = true
            },
            batchBindRoomUser() {
                batchBindRoomUser(this.roomUserForm).then(response => {
                    this.dialogRoomUserFormVisible = false
                }).catch(error => {
                    console.log(error)
                })
            },
            unBindRoomUser() {
                batchUnBindRoomUser(this.roomUserForm).then(response => {
                    this.listUser(this.$store.state.Navigation.pagination.current,
                        this.$store.state.Navigation.pagination.size)
                    this.$message.success("删除成功！");
                }).catch(error => {
                    console.log(error)
                    this.$message.success("删除失败！");
                })
            },
            roomTypeChange(gender) {
                if (gender == 1) {
                    let data = {
                        "gender": gender,
                        "type": this.roomUserForm.boy.roomType
                    }
                    listBuilding(data).then(response => {
                        this.boyBuildingList = response.data.buildings.records
                        console.log(this.boyBuildingList)
                    }).catch(error => {
                        console.log(error)
                    })
                }
                if (gender == 0) {
                    let data = {
                        "gender": gender,
                        "type": this.roomUserForm.girl.roomType
                    }
                    listBuilding(data).then(response => {
                        this.girlBuildingList = response.data.buildings.records
                        console.log(this.girlBuildingList)
                    }).catch(error => {
                        console.log(error)
                    })
                }

            },
            buildingNumChange(gender) {
                if (gender == 1) {
                    listRoomByBuildingId(this.roomUserForm.boy.buildingNum).then(response => {
                        this.boyRoomList = response.data.rooms
                    }).catch(error => {
                        console.log(error)
                    })
                }
                if (gender == 0) {
                    listRoomByBuildingId(this.roomUserForm.girl.buildingNum).then(response => {
                        this.girlRoomList = response.data.rooms
                    }).catch(error => {
                        console.log(error)
                    })
                }
            },
            handleSelectionChange(val) {
                this.roomUserForm.users = val
            }
        },
        created() {
            listOrgTree("0").then(response => {
                this.orgTree = response.data.orgTree
            }).catch(error => {
                console.log(error)
            })
            listRole().then(response => {
                this.roles = response.data.roles.records
            }).catch(error => {
                console.log(error)
            })
            this.listUser(this.$store.state.Navigation.pagination.current, this.$store.state.Navigation.pagination.size)
        }
    }
</script>

<style scoped>
    .platform-user {
        width: 100%;
        height: 100%;
    }

    .platform-user-org-tree {
        width: 200px;
        height: 100%;
        border-right: #cccccc 1px solid;
        float: left;
    }

    .platform-user-table {
        padding-left: 10px;
        width: calc(100% - 211px);
        height: 100%;
        float: left;
    }
</style>